package com.liliudong.template.api.admin.handler;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.SaTokenException;
import com.liliudong.template.common.R;
import com.liliudong.template.common.constant.ExMessageEnum;
import com.liliudong.template.common.exception.BizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.resource.NoResourceFoundException;

import java.util.stream.Collectors;


/**
 * 全局异常捕获
 *
 * @author ldli5
 * @classname GlobleExceptionHandler
 * @date 2024/6/18-15:05
 */
@Slf4j
@RestControllerAdvice
public class GlobleExceptionHandler {

	@ExceptionHandler(Exception.class)
	public R<?> exHandler(Exception e) {
		log.error(e.getMessage(), e);
		return R.error(ExMessageEnum.UNKNOWN_EXCEPTION);
	}

	@ExceptionHandler(NoResourceFoundException.class)
	@ResponseStatus(code = HttpStatus.NOT_FOUND)
	public R<?> exHandler(NoResourceFoundException e) {
		log.error(e.getMessage(), e);
		return R.error(ExMessageEnum.NOT_FOUND);
	}

	@ExceptionHandler(BizException.class)
	public R<?> exHandler(BizException e) {
		log.error(e.getMessage());
		return R.error(e.getExMessageEnum());
	}

	@ExceptionHandler(SaTokenException.class)
	public R<?> exHandler(SaTokenException e) {
		log.error(e.getMessage());
		return R.error(ExMessageEnum.TOKEN_EXCEPTION);
	}

	@ExceptionHandler(NotLoginException.class)
	@ResponseStatus(HttpStatus.UNAUTHORIZED)
	public R<?> exHandler(NotLoginException e) {
		log.error(e.getMessage());
		return R.error(ExMessageEnum.NOT_LOGIN_EXCEPTION);
	}

	@ExceptionHandler(NotPermissionException.class)
	@ResponseStatus(HttpStatus.FORBIDDEN)
	public R<?> exHandler(NotPermissionException e) {
		log.error(e.getMessage());
		return R.error(ExMessageEnum.NOT_PERMISSION_EXCEPTION);
	}

	@ExceptionHandler(BindException.class)
	public R<?> exHandler(BindException e) {
		String msg = e.getFieldErrors().stream()
				.map(fieldError -> {
					String field = fieldError.getField();
					String defaultMessage = fieldError.getDefaultMessage();
					return field + ":" + defaultMessage;
				}).collect(Collectors.joining(","));
		return R.error(msg);
	}

}
